
import re
import numpy as np


class RegexDict():
    def __init__(self,redict,judgekey):
        self.redict = redict
        self.judgekey = judgekey
    def main(self):
        for i in self.redict.keys():
            if re.search(i,self.judgekey):
                return self.redict[i]
        raise KeyError('not in dict')
class Tabletwo():
    def __init__(self,**params1):
        self.config = params1['config']
        self.get_money = params1['get_money']
    def table_get_data(self,data_dict,tag_ls):
        def main_get_data(data_direction,tag_ls,end_dict,num,original,mul_data_key):
            for mul_data_value in data_direction[num + 1:]:
                if mul_data_value not in tag_ls and re.search(RegexDict(self.config['need_keys_parttwo'], mul_data_key).main(),mul_data_value) != None:
                    if mul_data_key != '投标要求':
                        if re.search('^(投资额|预算金额|最高限价)',mul_data_key):
                            if '万元' in mul_data_key and '%' in mul_data_key:
                                money_unit = -1
                            elif '元' in mul_data_key and '%' in mul_data_key:
                                money_unit = -2
                            elif '万' in mul_data_key:
                                money_unit = 0
                            elif '%' in mul_data_key:
                                money_unit = 1
                            else:
                                money_unit = 2
                            if (re.search('^\d{1,20}\.?\d{0,20}（?万?元?）?$|[壹佰叁拾贰万贰仟捌佰元整]|^(\d{1,3}[,.]?){1,5}（?万?元?）?$',
                                          mul_data_value)):

                                if '金额' in mul_data_value:
                                    mul_data_value = mul_data_value.split('金额')[1]
                                if '元万元' in mul_data_value:
                                    mul_data_value = mul_data_value.replace('万元', '')
                                if '总价' in mul_data_value:
                                    mul_data_value = re.split('总价:?', mul_data_value)[1]
                                mul_data_value = re.sub('人民币|[，,。]|CNY', '', mul_data_value)
                                mul_data_value_x_ls = mul_data_value.split(' ')
                                if len(mul_data_value_x_ls) > 1:
                                    mul_data_value = ''
                                    for mul_data_value_xi in mul_data_value_x_ls:
                                        try:
                                            float(re.sub('[零壹贰貳叁肆伍陆柒捌玖拾分角元拾佰百仟圆]', '', mul_data_value_xi))
                                            mul_data_value += mul_data_value_xi
                                        except:
                                            continue
                                mul_data_value_x_ls = re.findall('\d+\.?\d{0,}万?元', mul_data_value)
                                mul_data_value_x_ = ''
                                if len(mul_data_value_x_ls) > 1:
                                    for mul_data_value_x_lsi in mul_data_value_x_ls:
                                        mul_data_value_x_ += mul_data_value_x_lsi + '；'
                                    mul_data_value = mul_data_value_x_

                                if '（' in mul_data_value and len(mul_data_value) <= 30:
                                    mul_data_value = mul_data_value.split('（')[0]

                                if money_unit in (-1, -2):
                                    tt_len = len(mul_data_value) if '.' not in mul_data_value else len(
                                        mul_data_value.split('.')[0])
                                    if tt_len <= 3:
                                        money_unit = 1
                                    else:
                                        if money_unit == -1:
                                            money_unit = 0
                                        elif money_unit == -2:
                                            money_unit = 2

                                if money_unit == 0:
                                    mul_data_value = re.sub('万元?', '',mul_data_value)
                                    try:
                                        ttt = str(float(self.get_money(mul_data_value)) * 10000)
                                    except:
                                        ttt = mul_data_value

                                elif money_unit == 1:
                                    try:
                                        if '元' not in mul_data_value and float(mul_data_value) <= 100:
                                            ttt = str(float(self.get_money(mul_data_value)) * 10000) + '%'
                                        else:
                                            ttt = str(self.get_money(mul_data_value))
                                    except:
                                        ttt = mul_data_value
                                elif money_unit == 2:
                                    try:
                                        ttt = str(self.get_money(mul_data_value))
                                    except:
                                        ttt = mul_data_value
                                mul_data_key = mul_data_key.split('（')[0]
                                end_dict[mul_data_key] = ttt
                            else:
                                end_dict[mul_data_key] = mul_data_value
                        else:
                            end_dict[mul_data_key] = mul_data_value
                    else:
                        end_dict[mul_data_key] = end_dict.get(mul_data_key,'') + '_' + mul_data_value
                        continue
                    end_dict[mul_data_key + '_original'] = original
                    break
                else:
                    break
            return end_dict
        def main_use(data_use_dict):
            end_dict = {}
            all_title_text_dict_ls_not_use = []
            for all_title_text_key in data_use_dict.keys():
                if (len(np.unique(data_use_dict[all_title_text_key]['x_data'])) == 1):
                    if data_use_dict[all_title_text_key]['y'] in all_title_text_dict_ls_not_use:
                        pass
                    else:
                        all_title_text_dict_ls_not_use.append(data_use_dict[all_title_text_key]['y'])

            for mul_data_key in list(data_use_dict.keys()):

                direction = data_use_dict[mul_data_key]['direction']
                y = data_use_dict[mul_data_key]['y']
                y = y if y <= 30 else 30
                if mul_data_key.split('{')[0] in end_dict:
                    continue

                if direction == 'None' or (y in all_title_text_dict_ls_not_use and mul_data_key.split('{')[0] != '投标要求'):
                    continue

                if mul_data_key in end_dict and mul_data_key != '投标要求':
                    continue
                x = data_use_dict[mul_data_key]['x']
                x_data = data_use_dict[mul_data_key]['x_data']
                y_data = data_use_dict[mul_data_key]['y_data']
                original = data_use_dict[mul_data_key]['original']
                mul_data_key = mul_data_key.split('{')[0]

                if direction == 'right':
                    end_dict = main_get_data(x_data, tag_ls, end_dict,x,original,mul_data_key)
                elif direction == 'down':
                    end_dict = main_get_data(y_data, tag_ls, end_dict,y,original,mul_data_key)


            return end_dict

        end_use_dict = {}
        for tag_key in data_dict.keys():
            if tag_key[:4] == 'data':
                end_use_dict[tag_key] = main_use(data_dict[tag_key])
            elif tag_key[:5] == 'table':
                end_use_dict[tag_key] = self.table_get_data(data_dict[tag_key], tag_ls)
        return end_use_dict

    def visible_concat(self,end_dict_pre):
        end_visible_dict = {}
        for tag_key in end_dict_pre.keys():
            if not isinstance(end_dict_pre[tag_key],dict):
                if tag_key not in end_visible_dict:
                    end_visible_dict[tag_key] = end_dict_pre[tag_key]
            else:
                tt = self.visible_concat((end_dict_pre[tag_key]))
                cc = tt.copy()
                for i in tt:
                    if i in end_visible_dict:
                        del cc[i]
                end_visible_dict.update(cc)
        return end_visible_dict

    def tender_to_name(self,visible_concat_data):
        if '标段' in visible_concat_data:
            if '项目名称' in visible_concat_data:
                visible_concat_data['项目名称'] = visible_concat_data['项目名称'] + '_' + visible_concat_data['标段']
                del visible_concat_data['标段']
        return visible_concat_data

    def province_city(self,visible_concat_data):

        region = ['项目地点','项目区域']
        for regioni in region:
            if regioni in visible_concat_data:
                for i in self.config['province']:
                    if i in visible_concat_data[regioni][:10]:
                        visible_concat_data['项目地点省份'] = i
                        break

                if '省' in visible_concat_data[regioni]:
                    obj = re.search('省(.*?)市',visible_concat_data[regioni])
                else:
                    obj = re.search('(.*?)市',visible_concat_data[regioni])
                if obj != None:
                    city = obj.group(1)
                    if '项目地点城市' not in visible_concat_data:
                        visible_concat_data['项目地点城市'] = city
        return visible_concat_data

    def project_quality(self,province_data):
        quolity_class = [['企业资质类别','企业资质要求'],['人员资格类别','人员资格要求']]
        for quolity_classi in quolity_class:
            if quolity_classi[0] in province_data:
                if quolity_classi[1] in province_data:
                    province_data[quolity_classi[1]] = province_data[quolity_classi[0]] + '·' + province_data[quolity_classi[1]]
                else:
                    province_data[quolity_classi[1]] = province_data[quolity_classi[0]]
                del province_data[quolity_classi[0]]

        if '投标要求' in province_data:
            company_quality = province_data['投标要求']
        else:
            company_quality = ''
        if '人员资格要求' in province_data:
            human_quality = '_' + province_data['人员资格要求']
        else:
            human_quality = ''
        if '其他资质要求' in province_data:
            other_quality = '_' + province_data['其他资质要求']
        else:
            other_quality = ''
        if human_quality != '' or company_quality != '' or other_quality != '':
            province_data['投标要求'] = company_quality + human_quality + other_quality
        return  province_data

    def cumunicate(self,quality_data):
        cumunicate_ls = ['联系人','联系电话']
        for cumunicatei in cumunicate_ls:
            if cumunicatei in quality_data and '业主'+cumunicatei not in quality_data:
                quality_data['业主'+cumunicatei] = quality_data[cumunicatei]
                del quality_data[cumunicatei]

        quality_data_ = quality_data.copy()
        for i in quality_data:

            if i[-4:] == '联系电话':
                ls = ['业主', '招标代理单位']
                for lsi in ls:
                    if lsi + '联系电话' in quality_data:
                        obj = re.search('联系人：?(.*?)(；|联系|\d)', quality_data[lsi + '联系电话'])
                        if obj:
                            quality_data_[lsi + '联系人'] = obj.group(1)

                        obj = re.search('联系电话：?(.*)(；|联系)?', quality_data[lsi + '联系电话'])
                        if obj:
                            quality_data_[lsi + '联系电话'] = obj.group(1)

                        if '联系人' in quality_data_[lsi + '联系电话']:
                            if lsi + '联系人' not in quality_data_:
                                quality_data_[lsi + '联系人'] = quality_data_[lsi + '联系电话'].split('联系人')[1]
                            quality_data_[lsi + '联系电话'] = quality_data_[lsi + '联系电话'].split('联系人')[0]

        quality_data = quality_data_
        return quality_data

    def communicate_number_clear(self,cumunicate_data):
        company = ['业主','招标代理单位']
        for i in company:
            if i + '联系电话' in cumunicate_data:
                obj = re.search('([^\d-]+)\s{0,}(\d{11}|\d{4}-\d{7}|\d{3}-\d{8})',cumunicate_data[i + '联系电话'])
                if obj:
                    cumunicate_data[i + '联系电话'] = obj.group(2)
                    if i + '联系人' not in cumunicate_data:
                        cumunicate_data[i + '联系人'] = obj.group(1)
            if i + '联系人' in cumunicate_data:
                obj = re.search('([^\d-]+)\s{0,}(\d{11}|\d{4}-\d{7}|\d{3}-\d{8})',cumunicate_data[i + '联系人'])
                if obj:
                    cumunicate_data[i + '联系人'] = obj.group(1)
                    if i + '联系电话' not in cumunicate_data:
                        cumunicate_data[i + '联系电话'] = obj.group(2)
        return cumunicate_data

    def especial_handle(self,cumunicate_data):
        cumunicate_data_ = cumunicate_data.copy()
        for i in cumunicate_data:
            if 'especial' in i:
                master = i.split('-especial')[0]
                if master not in cumunicate_data:
                    cumunicate_data_[master] = cumunicate_data[i]
                del cumunicate_data_[i]
        return cumunicate_data_

    def end_data_clear(self,communicate_number_clear_data):
        DateJudge = ['招标公告发布日期','报名截止日期','招标文件获取的时间']
        for DateJudgei in DateJudge:
            if DateJudgei in communicate_number_clear_data:
                DateJudgeObj = re.search('(\d{4}[-/年]\d{2}[-/年]\d{2})',communicate_number_clear_data[DateJudgei])
                if DateJudgeObj:
                    communicate_number_clear_data[DateJudgei] = DateJudgeObj.group() + ' ' + communicate_number_clear_data[DateJudgei].split(DateJudgeObj.group())[1]
        if '投标要求' in communicate_number_clear_data:
            obj = re.search('(?<!\d)\d[.．、]\d?(?!\d?[万元%])(?!\d{2,})|（?(?:[一二三四五六七八九十]|\d{1,2}(?!\d?[万元%]))）|[①②③④⑤]',communicate_number_clear_data['投标要求'])
            if obj:
                ls = re.split('(?<!\d)\d[.．、]\d?(?!\d?[万元%])(?!\d{2,})|（?(?:[一二三四五六七八九十]|\d{1,2}(?!\d?[万元%]))）|[①②③④⑤]',communicate_number_clear_data['投标要求'])
                for i in ls:
                    if isinstance(i, str):
                        if i in ['','1','一','.'] or re.search('^[一二三四五六七八九十]$|^\d[.、]?\d?$', i):
                            ls.remove(i)
                communicate_number_clear_data['投标要求'] = ls
            else:
                communicate_number_clear_data['投标要求'] = [communicate_number_clear_data['投标要求']]
        return communicate_number_clear_data

    def hezhun(self,communicate_number_clear_data):
        if '核准单位' in communicate_number_clear_data:
            obj = re.search('发改.*?号',communicate_number_clear_data['核准单位'])
            if obj:
                tt = obj.group()
                if '核准文号' not in communicate_number_clear_data:
                    communicate_number_clear_data['核准文号'] = tt
                communicate_number_clear_data['核准单位'] = re.sub(f'{tt}|[（）]', '', communicate_number_clear_data['核准单位'])
            else:
                obj = re.search('[-A-Za-z\d]{5,}',communicate_number_clear_data['核准单位'])
                if obj:
                    tt = obj.group()
                    if '核准文号' not in communicate_number_clear_data:
                        communicate_number_clear_data['核准文号'] = tt
                    communicate_number_clear_data['核准单位'] = re.sub(f'{tt}|[（）]','',communicate_number_clear_data['核准单位'])
        return  communicate_number_clear_data

    def meijie(self, end_dict):
        if '发布公告的媒介' in end_dict:
            end_dict['发布公告的媒介_来源链接'] = ''
            url = re.findall(r"(https|http)(.*?)(com|cn)", end_dict['发布公告的媒介'], re.S)
            for i in url:
                end_dict['发布公告的媒介'] = end_dict['发布公告的媒介'].replace(','.join(i).replace(',', ''), '').replace('（）', '')
            for n in url:
                end_dict['发布公告的媒介_来源链接'] = end_dict['发布公告的媒介_来源链接'] + ','.join(n).replace(',', '') + '、'
        return end_dict

    # def extract(self,end_dict):
    #     if '预算金额' in end_dict:
    #         obj = re.search('.*', end_dict['预算金额']).group()
    #         try:
    #             end_dict['预算金额'] = re.search('(\d+\.?\d+|\d+)万?元?%?', obj).group(1)
    #             if '最高限价' not in end_dict:
    #                 obj1 = re.search(r'(\d+\.\d+|\d+)[^\d]{1,}?(\d+\.\d+|\d+)万?元?%?', obj)
    #                 if obj1:
    #                     end_dict['最高限价'] = obj1.group(2)
    #         except Exception as e:
    #             print(e,'extract wrong')
    #     return end_dict

    def temp(self,end_data):
        end_data_ = end_data.copy()
        for i in end_data:
            if 'original' in i:
                del end_data_[i]
        return end_data_

    def supply(self,end_data):
        need_ls = ['项目名称', '标段','标的信息','业主名称', '业主联系人', '业主联系电话', '业主地址', '业主传真',
                   '招标代理单位名称', '招标代理单位联系人', '招标代理单位联系电话', '招标代理单位传真', '招标代理单位地址',
                   '工期', '项目类型', '项目地点', '项目地点城市', '项目地点省份', '建设规模', '招标公告发布日期', '报名截止日期',
                   '投标要求', '发布公告的媒介', '评标成员','招标文件获取的时间','招标文件获取的地点','招标文件获取的方法','招标文件获取的售价','获取招标文件','资金来源',
                    '开标地点','标段划分','招标范围','投资额','采购需求','是否接受联合体','开标地点','发布公告的媒介_来源链接','开标时间','核准文号','采购方式','最高限价',
                   '预算金额','代理服务收费标准及金额','项目编号','核准单位','合同履行期限']


        for i in need_ls:
            if i not in end_data:
                end_data[i] = '' if i != '投标要求' else []
        return end_data
    def kaibregion(self,communicate_number_clear_data):
        if '报名截止日期' in communicate_number_clear_data:
            if '地点' in communicate_number_clear_data['报名截止日期']:
                if '开标地点' not in communicate_number_clear_data or communicate_number_clear_data['开标地点'] == '':
                    communicate_number_clear_data['开标地点'] = communicate_number_clear_data['报名截止日期'].split('地点')[1]
                    communicate_number_clear_data['报名截止日期'] =  communicate_number_clear_data['报名截止日期'].split('地点')[0]
        return communicate_number_clear_data

    def part_two_table(self,data_dict,tag_ls):
        end_dict_pre = self.table_get_data(data_dict,tag_ls)
        # print(end_dict_pre)
        visible_concat_data = self.visible_concat(end_dict_pre)

        visible_concat_data = self.tender_to_name(visible_concat_data)
        visible_concat_data = self.especial_handle(visible_concat_data)
        province_data = self.province_city(visible_concat_data)
        quality_data = self.project_quality(province_data)
        cumunicate_data = self.cumunicate(quality_data)
        communicate_number_clear_data = self.communicate_number_clear(cumunicate_data)
        communicate_number_clear_data = self.hezhun(communicate_number_clear_data)
        communicate_number_clear_data = self.meijie(communicate_number_clear_data)
        # communicate_number_clear_data = self.extract(communicate_number_clear_data)
        communicate_number_clear_data = self.kaibregion(communicate_number_clear_data)
        communicate_number_clear_data = self.end_data_clear(communicate_number_clear_data)
        end_data = communicate_number_clear_data
        end_data = self.supply(end_data)
        end_data['which_part'] = 'Two'
        end_data = self.temp(end_data)

        return end_data
